package com.hlxt.nj.sys.action;


import com.alibaba.fastjson.JSON;
import com.hlxt.nj.common.*;
import com.hlxt.nj.sys.model.TUser;
import com.hlxt.nj.sys.service.TUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("/user")
public class UserAction extends BaseAction{

    @Autowired
    TUserService tUserService;

    /**
     * 查询用户信息
     * @param username
     * @param loginname
     * @param email
     * @param mobilephone
     * @param userstate
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/query.do")
    public ModelAndView query(String username, String loginname, String email, String mobilephone, String userstate) {
        // 获取分页
        PageBean pageBean = getPageBean();
        TUser user=new TUser();
        if(!StringUtil.isEmpty(username)){
            user.setUsername(username);
        }
        if(!StringUtil.isEmpty(loginname)){
            user.setLoginname(loginname);
        }

        if(!StringUtil.isEmpty(mobilephone)){
            user.setPnumber(mobilephone);
        }

        tUserService.queryPageList(user, pageBean);
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("rows", pageBean.getResults());
        map.put("total", pageBean.getTotalRecords());
        String json = JSON.toJSONString(map);
        return new ModelAndView("jsonView", "ajax_json", json);
    }

    /**
     * 创建用户
     * @param user
     * @return
     */
    @RequestMapping("/add.do")
    @ResponseBody
    public RespMessage add(TUser user) {
        if (!StringUtil.isEmpty(user.getLoginname(),
                user.getPnumber(), user.getUsername())
                && user.getLoginname().matches(BusiConst.REGExp_LOGINNAME)
                && user.getPnumber().matches(BusiConst.REGExp_MOBILEPHONE)
                && user.getUsername().matches(BusiConst.REGExp_CH)
                && user.getLoginname().length()<=16
                && user.getUsername().length()<=16) {
            if (isUserExist(user.getPnumber(),user.getUsername())) {
                log.info("添加用户失败,用户已存在,pnumber="+user.getPnumber());
                return RespMessageUtil.getResp(RetCodeDef.USER_LOGINNAME_EXIST, "");
            } else {
                String userid =TimeUtil.date8().substring(2, 8)+SequenceUtil.formatSequence(SequenceUtil.getInstance()
                        .getSequence4File("t_course"), 10);
                user.setUsrid(userid);
                boolean rs = tUserService.add(user);
                if (rs) {
                    log.info("添加用户成功,loginname="+user.getLoginname());
                    return RespMessageUtil.getResp(RetCodeDef.SUCCESS, "");
                } else {
                    log.info("添加用户失败,SQL异常,loginname="+user.getLoginname());
                    return RespMessageUtil.getResp(RetCodeDef.SQL_ERROR, "");
                }
            }
        } else {
            log.info("添加用户失败,参数鉴权失败");
            return RespMessageUtil.getResp(RetCodeDef.PARA_AUTH_FAIL, "");
        }
    }


    /**
     * 修改用户基本信息
     * @param userid
     * @param username
     * @param mobilephone
     * @param loginname
     * @return
     */
    @RequestMapping("/update.do")
    @ResponseBody
    public RespMessage update(String userid,String username,String mobilephone,
                              String loginname) {
        if (!StringUtil.isEmpty( mobilephone,username, userid,loginname)
                && loginname.matches(BusiConst.REGExp_LOGINNAME)
                && mobilephone.matches(BusiConst.REGExp_MOBILEPHONE)
                && username.matches(BusiConst.REGExp_CH)
                && userid != getUser().getUsrid()
                && username.length()<=16) {
            TUser user = new TUser();
            user.setUsrid(userid);
            user.setUsername(username);
            user.setPnumber(mobilephone);
            boolean count = tUserService.update(user);
            if (count) {
                log.info("修改用户信息成功,id=" + userid);
                return RespMessageUtil.getResp(RetCodeDef.SUCCESS, "");
            } else {
                log.info("修改用户信息失败,SQL异常,id=" + userid);
                return RespMessageUtil.getResp(RetCodeDef.SQL_ERROR, "");
            }
        } else {
            log.info("修改用户信息失败，参数鉴权失败");
            return RespMessageUtil.getResp(RetCodeDef.PARA_AUTH_FAIL, "");
        }
    }



    /**
     * 重置用户登陆密码
     * @param userid
     * @param loginname
     * @return
     */
    @RequestMapping("/resetUserPassword.do")
    @ResponseBody
    public RespMessage resetUserPassword(String userid,String loginname) {
        if (!StringUtil.isEmpty(userid,loginname) && userid != getUser().getUsrid()) {
            TUser user =new TUser();
            String password = new MD5().toMD5(loginname + BusiConst.DEFAULT_PASSWORD);
            user.setLoginname(loginname);
            user.setUsrid(userid);
            user.setPssword(password);
            boolean count = tUserService.update(user);
            if (count ) {
                log.info("用户密码重置成功,loginname="+loginname);
                return RespMessageUtil.getResp(RetCodeDef.SUCCESS, "");
            } else {
                log.info("用户密码重置成功失败,SQL异常,loginname="+loginname);
                return RespMessageUtil.getResp(RetCodeDef.SQL_ERROR, "");
            }
        } else {
            log.info("用户密码重置成功失败,参数鉴权失败");
            return RespMessageUtil.getResp(RetCodeDef.PARA_AUTH_FAIL, "");
        }
    }



    /**
     * 修改密码
     * @param password
     * @param newPWD
     * @return
     */
    @RequestMapping("/editUserPassword.do")
    @ResponseBody
    public RespMessage editUserPassword(String password,String newPWD) {
        //参数鉴权
        if(StringUtil.isEmpty(password) || StringUtil.isEmpty(newPWD) || password.length()>16 || newPWD.length()>16){
            log.info("修改密码失败,参数鉴权失败");
            return RespMessageUtil.getResp(RetCodeDef.PARA_AUTH_FAIL, "");
        }
        TUser user =new TUser();
        //1.从session中获取loginname
        HttpSession session=getHttpSession();
        String loginName = (String)session.getAttribute("loginName");
        //2.根据loginname查找用户
        user=tUserService.findByLoginname(loginName);
        //3.校验原密码
        password = new MD5().toMD5(loginName + password);//根据加密规则进行MD5计算
        if(!password.equals(user.getPssword())){  //如果原密码错误，直接返回
            log.info("修改密码失败,原密码错误,loginName="+loginName);
            return RespMessageUtil.getResp(RetCodeDef.USER_OLD_PASSWORD_INCORRECT, "");
        }
        String newpwd = new MD5().toMD5(loginName + newPWD);
        user.setPssword(newpwd);
        boolean count = tUserService.update(user);
        if (count) {
            log.info("修改密码成功,loginName="+loginName);
            return RespMessageUtil.getResp(RetCodeDef.SUCCESS, "");
        } else {
            log.info("修改密码失败,SQL异常,loginName="+loginName);
            return RespMessageUtil.getResp(RetCodeDef.PARA_AUTH_FAIL, "");
        }
    }


    /**
     * 校验pNumber是否重复
     * @param pNumber
     * @return
     */
    private boolean isUserExist(String pNumber,String username) {
        boolean flag = false;

        TUser u = tUserService.findByPnumber(pNumber,username);
        if (u != null) {
            flag = true;
        }
        return flag;
    }

}
